//
//  WBMainViewController.swift
//  新浪微博
//
//  Created by apple on 2016/11/29.
//  Copyright © 2016年 yanjun. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBMainViewController: UITabBarController {

    // 定时器
    
    fileprivate var timer: Timer?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupChildControllers()
        
        setupComposeButotn()
        
        
        setupTimer()
        
        setupNewfeatureViews()
        
        // 设置代理
        delegate = self

        // 注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userlogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
        
    }
    
    
    
    
    deinit {
        // 销毁时钟
        timer?.invalidate()
        
        NotificationCenter.default.removeObserver(self)
    }
    

    // MARK: - 监听方法
    
    @objc private func userlogin(n: Notification) {
        
        print("通知")
        
        var when = DispatchTime.now()
        
        // 判断n.object 是否有值，如果有值，提示用户重新登录
        if n.object != nil {
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "用户登录已经超时,需要重新登录")
            
            when = DispatchTime.now() + 2
        }
        
        DispatchQueue.main.asyncAfter(deadline: when, execute: {
            
            SVProgressHUD.setDefaultMaskType(.clear)
        
            // 展现登录控制器
            let nav = UINavigationController(rootViewController: WBOAuthViewController())
            
            self.present(nav, animated: true, completion: nil)
        })
        
        
    }
    
    
     func composeStatus() {
        print("撰写微博")
    }

    // MARK: - 私有控件
    
    lazy var composeButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")

    /**
     portrait  : 竖屏，肖像
     landscape : 横屏，风景画
     - 使用代码控制设备的方向
     - 设置支持的方向时候，当前的控制器及子控制器都会遵守这个方向
     */
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask
        {
            return .portrait
    }
    
}

// MARK: - UITabBarControllerDelegate
extension WBMainViewController: UITabBarControllerDelegate
{
    
    
    /// 将要选择 TabBarItem
    ///
    /// - Parameters:
    ///   - tabBarController: tabBarController
    ///   - viewController: 目标控制器
    /// - Returns: 时候切换到目标控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        print(viewController)
        
        // 1> 获取控制器在数组中的索引
        let index = (childViewControllers as NSArray).index(of: viewController)
        
        // 2> 判断当前索引是首页，同时 index 也是首页，重复点击首页的按钮
        if selectedIndex == 0 && index == selectedIndex {
        
            print("首页")
            // 3> 让表格滚动到顶部
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! WBHomeViewController
            
            // 滚动到顶部
            vc.tableView?.setContentOffset(CGPoint(x:0,y:-64), animated: true)
            
            // 4> 刷新数据
            // 增加延迟，保证表格先滚动搞顶部再刷新
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { 
                
                vc.loadData()
            })
            
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
            
        }
        
        
        
        // 判断目标控制器是否是 UIViewController
        return !viewController.isMember(of: UIViewController.self)
    }
    
    
}


// MARK: - 时钟方法
extension WBMainViewController {
    
    fileprivate func setupTimer() {
    
        timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    
    }
    
    @objc private func updateTimer() {
        
        if !WBNetworkManager.shared().userLogon {
            return
        }
        
        WBNetworkManager.shared().unReadCount { (count) in

            print("有\(count)微博")
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            
            // 从ios8开始要用户授权才会显示
            UIApplication.shared.applicationIconBadgeNumber = count

        }
        
    }
    
}

extension WBMainViewController {
    
    fileprivate func setupNewfeatureViews() {
        
        // 判断是否登录
       if !WBNetworkManager.shared().userLogon {
            return
        }
        
        let v = isNewVersion ? WBNewFeature.WBNewFeature() : WBWelcome.welcomeView()
        
        v.frame = view.bounds
        
        view.addSubview(v)
        
    }
    
    // extension 中可以有计算型属性，不会占用存储空间
    // 构造函数：给属性分配空间
    fileprivate var isNewVersion: Bool {
        
        
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        
        let path: String = ("version" as NSString).cz_appendDocumentDir()
        let sandboxVerson = (try? String(contentsOfFile: path)) ?? ""
        
        try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        // 不一样就是新版本
        return currentVersion != sandboxVerson
        
    }
    
}

// extension 类似于 oc 的分类，在 swift 中还可以用来切分代码块
// 可以把相近功能的函数，放在一个 extension 中，便于代码维护
// 注意： 和OC一样，extension 不能定义属性

// MARK: - 设置界面
extension WBMainViewController {
    
    func setupComposeButotn() {
        tabBar.addSubview(composeButton)
        
        // 计算按钮的宽度
        let count = CGFloat(childViewControllers.count)
        
        // 向内缩进的宽度
        let w = tabBar.bounds.width / count
        
        
        composeButton.frame = tabBar.bounds.insetBy(dx: 2*w, dy: 0)
        
        composeButton.addTarget(self, action: #selector(composeStatus), for: UIControlEvents.touchUpInside)
    }
    
    
    func setupChildControllers() {
        
        // 0.获取沙盒 json 路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        
        let jsonPath = (docDir as NSString).appendingPathComponent("main,json")
        
        // 加载data
        var data = NSData(contentsOfFile: jsonPath)
        
        // 判断data是否有内容，如果没有说明本地沙盒没有文件
        if data == nil {
            // 从 bundle 加载data
           let path = Bundle.main.path(forResource: "main.json", ofType: nil)
        
            data = NSData(contentsOfFile: path!)
        }
        
        // data 一定会有一个内容，反序列化
        
        // 从 bundle 加载配置 json
        /**
           throw 抛出异常
           方法一：推荐 try? 如果解析成功就有值，否则为 nil
           方法二：强烈不推荐 try! 如果解析成功就有值，否则崩溃
           方法三：处理异常,能够接受到错误，并且输出错误，但是语法结构复杂
           do {
         
           }catch {
         
           }
         */
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: Any]] else {
            return
        }
        
        // 建立数组，循环创建控制器数组
        var arrayM = [UIViewController]()
        
        for dict in array! {
            arrayM.append(controller(dict: dict))
        }
        
        // 设置 tabBar 的子控制器
        viewControllers = arrayM
        
    }
    
    // 子控制器
    private func controller(dict: [String: Any]) -> UIViewController{
        
        guard let clsName = dict["clsName"] as? String, let title = dict["title"] as? String, let imageName = dict["imageName"] as? String,let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,let visitorDict = dict["visitorInfo"] as? [String:String] else {
        
            
            
            return UIViewController()
        }
        
        
        let vc = cls.init()
        vc.title = title;
        
        // 设置控制器的访客信息字典
        vc.visitorInfo = visitorDict
        
        
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
        
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: UIControlState.highlighted)
        // 设置字体大小
        // vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 13)], for: UIControlState.normal)
        
        // 实例化导航控制器的时候会调用 push 方法将 rootVC 压栈
        let nav = WBNavigationController(rootViewController: vc);
        return nav
        
        
    }
    
    
}
